package com.rpa.server.servicerpaserver.crawler.operate;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rpa.secure.servicerpasecure.common.constant.MessageConstant;
import com.rpa.secure.servicerpasecure.common.constant.ParameterConstant;
import com.rpa.secure.servicerpasecure.common.constant.UrlConstant;
import com.rpa.secure.servicerpasecure.common.exception.TaskException;
import com.rpa.secure.servicerpasecure.common.util.CurrentTeacherInfoUtil;
import com.rpa.server.servicerpaserver.crawler.entity.Course;
import com.rpa.server.servicerpaserver.crawler.entity.User;
import com.rpa.server.servicerpaserver.crawler.service.CourseService;
import com.rpa.server.servicerpaserver.crawler.service.UserService;
import com.rpa.server.servicerpaserver.crawler.service.impl.UerServiceImpl;
import com.rpa.server.servicerpaserver.pojo.Cookies;
import com.rpa.server.servicerpaserver.util.CookieSerialize;
import com.rpa.server.servicerpaserver.util.WebDriverUtil;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @className: CourseOperate
 * @author: lzt
 * @date: 2025/1/10 10:35
 * @Version: 1.0
 * @description:
 */
@Component
@Slf4j
public class CourseOperate {
    @Autowired
    private CookieSerialize cookieSerialize;
    @Autowired
    private UserService uerService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private RedissonClient redissonClient;

    @Async("getNameAndPictureTaskExecutor")
    public CompletableFuture<Boolean>  getNameAndPicture(String rpaRegisterId) {
        log.info("开始获取头像、名字");
        User user = uerService.getById(rpaRegisterId);
        if (user == null) {
            throw new TaskException(MessageConstant.NO_USER);
        }
        ChromeOptions options = new ChromeOptions();
        WebDriverUtil.setupWebDriver(options);
        ChromeDriver chromeDriver = null;
        try {
            chromeDriver = new ChromeDriver(options);
            cookieSerialize.goFZF(rpaRegisterId+"WORK", ParameterConstant.ROUTE_WIDGET,chromeDriver);
            chromeDriver.get(UrlConstant.I_CAHOXING);
            cookieSerialize.delAfterSaveCookies(rpaRegisterId+"WORK", chromeDriver.manage().getCookies());
            WebDriverWait webDriverWait = new WebDriverWait(chromeDriver, Duration.ofSeconds(5));
            webDriverWait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[@id=\"mainphoto\"]")));
            WebElement srcElement = chromeDriver.findElement(By.xpath("//*[@id=\"mainphoto\"]"));
            String src = srcElement.getAttribute("src");
            WebElement nameElement = chromeDriver.findElement(By.xpath("//*[@id=\"space_nickname\"]/p"));
            String name = nameElement.getText();
            user.setXingName(name).setXingPictureImgSrc(src);
            boolean isSuccess  = uerService.updateById(user);
            if (isSuccess){
                log.info("用户：{}，获取头像、名字成功，用户id为：{}", user.getXingAccount(),user.getId());
                return CompletableFuture.completedFuture(true);
            }else {
                log.info("用户：{}，获取头像、名字失败，用户id为：{}", user.getXingAccount(),user.getId());
                return CompletableFuture.completedFuture(false);
            }
        }catch (Exception e){
            log.error("获取头像、名字失败，异常信息为:{}",e);
        }finally {
            WebDriverUtil.closeWebDriver(chromeDriver);
        }
        return CompletableFuture.completedFuture(false);
    }
    @Async("getCourseTaskExecutor")
    public CompletableFuture<Boolean> getCourse(String rpaRegisterId) {
        log.info("开始获取课程");
        ChromeOptions options = new ChromeOptions();
        WebDriverUtil.setupWebDriver(options);
        ChromeDriver chromeDriver = null;
        try {
            chromeDriver = new ChromeDriver(options);
            cookieSerialize.goFZF(rpaRegisterId+"WORK", ParameterConstant.ROUTE_WIDGET,chromeDriver);
            chromeDriver.get(UrlConstant.I_CAHOXING);
            cookieSerialize.delAfterSaveCookies(rpaRegisterId+"WORK", chromeDriver.manage().getCookies());
            WebDriverWait webDriverWait = new WebDriverWait(chromeDriver, Duration.ofSeconds(5));
            // 切换到iframe
            chromeDriver.switchTo().frame("frame_content");
            webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"courseList\"]")));
            WebElement divElement = chromeDriver.findElement(By.xpath("//*[@id=\"courseList\"]"));
            List<WebElement> courseElements = divElement.findElements(By.cssSelector(".course.clearfix.teachCourse"));
            for (WebElement webElement : courseElements) {
                WebElement courseIdElement = webElement.findElement(By.xpath("."));
                String courseId = courseIdElement.getAttribute("id").substring(2);
                WebElement imgElement = webElement.findElement(By.tagName("img"));
                String srcCourse = imgElement.getAttribute("src");
                WebElement courseNameElement = webElement.findElement(By.xpath(".//div[@class=\"course-info\"]//span[@class=\"course-name overHidden2\"]"));
                String nameCourse = courseNameElement.getText();
                WebElement coursePrincipalElement = webElement.findElement(By.xpath(".//div[@class=\"course-info\"]//p[@class=\"line2 color3\"]"));
                String coursePrincipal = coursePrincipalElement.getText();
                String teacherId = rpaRegisterId;
                Course rpaCourse = Course.builder()
                        .courseName(nameCourse)
                        .courseImgSrc(srcCourse)
                        .coursePrincipal(coursePrincipal)
                        .courseId(courseId)
                        .accountId(Long.valueOf(teacherId))
                        .build();
                LambdaQueryWrapper<Course> rpaCourseLambdaQueryWrapper=new LambdaQueryWrapper<>();
                rpaCourseLambdaQueryWrapper.eq(Course::getAccountId,teacherId)
                        .eq(Course::getCourseId,courseId);
                 courseService.remove(rpaCourseLambdaQueryWrapper);
                 courseService.save(rpaCourse);
            }
        }catch (Exception e){
            log.error("获取课程失败，异常信息为:{}",e);
            return CompletableFuture.completedFuture(false);
        }finally {
            WebDriverUtil.closeWebDriver(chromeDriver);
        }
        return CompletableFuture.completedFuture(true);
    }
}
